<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="病虫草害记录"></page-header>

        <!-- 搜索栏 -->
        <view class="search-box">
            <uni-search-bar
                placeholder="请输入要搜索的作物内容"
                v-model="searchText"
                @confirm="handleSearch"></uni-search-bar>
        </view>

        <!-- 筛选选项卡 -->
        <filter-tabs :active-tab="activeTab" @tab-change="handleFilterChange"></filter-tabs>

        <!-- 记录列表 -->
        <view class="comm-record-list">
            <template v-if="filteredDiseaseRecords.length > 0">
                <record-item
                    v-for="(item, index) in filteredDiseaseRecords"
                    :key="index"
                    :item="item"
                    @clickItem="editRecord(item.id)"
                    @edit="editRecord(item.id)"
                    @delete="deleteRecord(item.id)">
                    <template #header>
                        <view class="item-header">
                            <view style="display: flex; align-items: center">
                                <image
                                    style="margin-right: 10rpx"
                                    class="icon-wrapper"
                                    src="/static/images/zacao.png"
                                    mode="aspectFill"
                                    v-if="item.pestTypeName === '杂草'"></image>
                                <image
                                    style="margin-right: 10rpx"
                                    class="icon-wrapper"
                                    src="/static/images/jibing.png"
                                    mode="aspectFill"
                                    v-if="item.pestTypeName === '疾病'"></image>
                                <image
                                    style="margin-right: 10rpx"
                                    class="icon-wrapper"
                                    src="/static/images/haichong.png"
                                    mode="aspectFill"
                                    v-if="item.pestTypeName === '害虫'"></image>
                                <view class="date-title">
                                    {{ item.pestTypeName }}-{{ item.pestName }}
                                </view>
                            </view>
                            <view
                                class="severity-tag"
                                :class="getSeverityClass(item.severityLevel)">
                                {{ getSeverityName(item.severityLevel) }}
                            </view>
                        </view>
                    </template>

                    <template #content>
                        <view class="item-content">
                            <view style="display: flex; justify-content: space-between">
                                <view class="info-row">
                                    <text class="info-label">受害面积:</text>
                                    <text class="info-value">{{ item.area }}亩</text>
                                </view>
                                <view class="info-row">
                                    <text class="info-label">地块位置:</text>
                                    <text class="info-value">
                                        {{ item.plotName }}-{{ item.fieldName }}
                                    </text>
                                </view>
                            </view>

                            <view class="info-row">
                                <text class="info-label">处理方案:</text>
                                <text class="info-value">{{ item.remarks || '暂无' }}</text>
                            </view>
                            <view class="info-row">
                                <text class="info-label">备注</text>
                                <text class="info-value">{{ item.remark }}</text>
                            </view>

                            <view
                                class="item-images"
                                v-if="item.imageList && item.imageList.length > 0">
                                <image
                                    v-for="(img, imgIndex) in item.imageList"
                                    :key="imgIndex"
                                    :src="img"
                                    mode="aspectFill"
                                    @click="previewImage(item.imageList, imgIndex)"></image>
                            </view>
                        </view>
                    </template>
                </record-item>

                <!-- 加载更多提示 -->
                <view class="load-more-container" v-if="filteredDiseaseRecords.length > 0">
                    <view v-if="loadingMore" class="loading-more">
                        <text class="loading-text">加载中...</text>
                    </view>
                    <view v-else-if="!hasMore" class="no-more">
                        <text class="no-more-text">没有更多数据了</text>
                    </view>
                </view>
            </template>
        </view>
        <!-- 空状态 -->
        <empty-data v-if="filteredDiseaseRecords.length === 0 && !loading"></empty-data>

        <!-- 添加按钮 -->
        <view
            class="add-button"
            @click="navigateTo('/pages/agriculture/diseaseManagement/addDisease')">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { pestDisease } from '@/utils/api/index.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    name: 'DiseaseManagement',
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            searchText: '',
            activeTab: 'all',
            activeType: 'all',
            startDate: '',
            endDate: '',
            plotId: '',
            fieldId: '',
            diseaseRecords: [],
            pageNo: 1,
            pageSize: 30,
            total: 0,
            loading: false,
            loadingMore: false,
            hasMore: true,
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
        filteredDiseaseRecords() {
            let records = this.diseaseRecords

            // 搜索过滤
            if (this.searchText) {
                const searchLower = this.searchText.toLowerCase()
                records = records.filter(
                    (record) =>
                        (record.pestName && record.pestName.toLowerCase().includes(searchLower)) ||
                        (record.pestTypeName &&
                            record.pestTypeName.toLowerCase().includes(searchLower))
                )
            }

            // 类型过滤
            if (this.activeType !== 'all') {
                records = records.filter((record) => record.pestType === this.activeType)
            }

            return records
        },
    },
    onShow() {
        // 加载字典数据
        this.loadDictData()
        // 加载列表数据
        this.loadDiseaseRecords()
    },
    onPullDownRefresh() {
        // 下拉刷新
        this.refreshList()
        setTimeout(() => {
            uni.stopPullDownRefresh()
        }, 1000)
    },
    // 触底加载更多
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                // 加载病虫草害类型字典
                await this.getDictByType('pests_diseases_weeds_type')
            } catch (error) {
                console.error('加载字典数据失败:', error)
            }
        },

        // 加载病虫害记录列表
        async loadDiseaseRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                }

                const params = {
                    pageNo: this.pageNo,
                    pageSize: this.pageSize,
                }

                // 添加筛选条件
                if (this.startDate) params.startDate = this.startDate
                if (this.endDate) params.endDate = this.endDate
                if (this.plotId) params.plotId = this.plotId
                if (this.activeType !== 'all') params.pestType = this.activeType

                const res = await pestDisease.getPestDiseasePage(params)

                if (res.code === 0 && res.data) {
                    const newList = res.data.list.map((item) => {
                        // 处理图片数据
                        let imageList = []
                        if (item.images) {
                            if (typeof item.images === 'string') {
                                imageList = item.images.split(',')
                            } else if (Array.isArray(item.images)) {
                                imageList = item.images
                            }
                        }

                        return {
                            ...item,
                            imageList,
                        }
                    })

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.diseaseRecords = [...this.diseaseRecords, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.diseaseRecords = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageSize
                    this.total = res.data.total
                }
            } catch (error) {
                console.error('获取病虫害记录失败:', error)
                uni.showToast({
                    title: '获取数据失败',
                    icon: 'none',
                })
            } finally {
                this.loading = false
                this.loadingMore = false
            }
        },

        // 刷新列表
        refreshList() {
            this.pageNo = 1
            this.hasMore = true
            this.loadDiseaseRecords()
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageNo += 1
            await this.loadDiseaseRecords(true)
        },

        // 搜索处理
        handleSearch() {
            this.pageNo = 1
            this.hasMore = true
            this.loadDiseaseRecords()
        },

        // 筛选选项卡变化
        handleFilterChange(tabValue, filterData) {
            this.activeTab = tabValue
            // 重置页码
            this.pageNo = 1
            this.hasMore = true
            // 清除之前的日期和地块筛选条件
            this.startDate = ''
            this.endDate = ''
            this.plotId = ''
            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.startDate = filterData.startDate
                    this.endDate = filterData.endDate
                }
                if (filterData.areaId) {
                    this.plotId = filterData.areaId
                }
            }
            // 重新请求接口
            this.loadDiseaseRecords()
        },

        // 设置活动类型
        setActiveType(type) {
            this.activeType = type
            this.pageNo = 1
            this.hasMore = true
            this.loadDiseaseRecords()
        },

        // 获取危害程度名称
        getSeverityName(severity) {
            const severities = {
                2: '轻度',
                1: '中度',
                0: '严重',
            }
            return severities[severity] || '未知'
        },

        // 获取危害程度CSS类
        getSeverityClass(severity) {
            const classes = {
                2: 'mild',
                1: 'medium',
                0: 'severe',
            }
            return classes[severity] || ''
        },

        // 格式化日期
        formatDate(date) {
            const year = date.getFullYear()
            const month = (date.getMonth() + 1).toString().padStart(2, '0')
            const day = date.getDate().toString().padStart(2, '0')
            return `${year}-${month}-${day}`
        },

        // 编辑记录
        editRecord(id) {
            uni.navigateTo({
                url: `/pages/agriculture/diseaseManagement/addDisease?id=${id}`,
            })
        },

        // 删除记录
        deleteRecord(id) {
            uni.showModal({
                title: '确认删除',
                content: '确定要删除这条病虫草害记录吗？',
                success: async (res) => {
                    if (res.confirm) {
                        try {
                            const result = await pestDisease.deletePestDiseaseRecord(id)

                            if (result.code === 0) {
                                uni.showToast({
                                    title: '删除成功',
                                    icon: 'success',
                                })
                                this.refreshList()
                            } else {
                                uni.showToast({
                                    title: result.msg || '删除失败',
                                    icon: 'none',
                                })
                            }
                        } catch (error) {
                            console.error('删除记录失败:', error)
                            uni.showToast({
                                title: '删除失败',
                                icon: 'none',
                            })
                        }
                    }
                },
            })
        },

        // 预览图片
        previewImage(images, current) {
            uni.previewImage({
                urls: images,
                current: current,
            })
        },

        // 页面导航
        navigateTo(url) {
            uni.navigateTo({ url })
        },
    },
}
</script>

<style lang="scss">
.severity-tag {
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    font-size: 24rpx;

    &.mild {
        background-color: #e8f5e9;
        color: #4caf50;
    }

    &.medium {
        background-color: #fff3e0;
        color: #ff9800;
    }

    &.severe {
        background-color: #ffebee;
        color: #f44336;
    }
}
</style>
